package com.hanserwei.han_picture.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hanserwei.han_picture.domain.entity.po.Picture;
import com.hanserwei.han_picture.manager.RedisManager;
import com.hanserwei.han_picture.mapper.PictureMapper;
import com.hanserwei.han_picture.utils.ImageTagsGenerateUtil;
import com.hanserwei.han_picture.websocket.WebSocketMessageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * 异步AI处理服务
 *
 * @author hanserwei
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class AsyncAiProcessService {

    private final PictureMapper pictureMapper;
    private final RedisManager redisManager;
    private final WebSocketMessageService webSocketMessageService;

    /**
     * 异步处理图片AI标签和分类生成
     *
     * @param pictureId  图片ID
     * @param pictureUrl 图片URL
     * @param needAiTile 是否需要AI生成标题
     * @param userId     用户ID，用于WebSocket通知
     */
    @Async("aiProcessExecutor")
    public void processAiTagsAndCategory(Long pictureId, String pictureUrl, boolean needAiTile, Long userId) {
        try {
            log.info("开始异步处理图片AI标签生成，图片ID: {}, URL: {}, 用户ID: {}", pictureId, pictureUrl, userId);

            pictureUrl = StrUtil.replace(pictureUrl, "cdncos.likeyy.love", "cos.likeyy.love");

            // 通知前端开始处理
            if (userId != null) {
                webSocketMessageService.notifyAiProcessStart(userId, pictureId);
            }

            // 调用AI生成标签和分类
            ImageTagsGenerateUtil.ImageTagsAndTile imageTagsAndTile =
                    ImageTagsGenerateUtil.getTagsAndTile(pictureUrl);

            // 获取当前图片信息
            Picture picture = pictureMapper.selectById(pictureId);
            if (picture == null) {
                log.warn("图片不存在，跳过AI处理，图片ID: {}", pictureId);
                return;
            }

            // 更新图片信息
            Picture updatePicture = new Picture();
            updatePicture.setId(pictureId);

            // 如果当前没有标签，则设置AI生成的标签
            if (picture.getTags() == null || picture.getTags().isEmpty() || "[]".equals(picture.getTags())) {
                updatePicture.setTags(JSONUtil.toJsonStr(imageTagsAndTile.tags()));

                // 将标签存储到Redis
                if (imageTagsAndTile.tags() != null && !imageTagsAndTile.tags().isEmpty()) {
                    redisManager.incrementTagsScore(imageTagsAndTile.tags(), 1.0);
                }
            }

            // 如果当前没有分类，则设置AI生成的分类
            if (picture.getCategory() == null || picture.getCategory().isEmpty()) {
                updatePicture.setCategory(imageTagsAndTile.category());
            }

            // 如果当前没有名称，则设置AI生成的标题
            if (needAiTile) {
                updatePicture.setName(imageTagsAndTile.title());
            }

            // 更新数据库
            int updateCount = pictureMapper.updateById(updatePicture);
            if (updateCount > 0) {
                log.info("异步AI处理完成，图片ID: {}, 标签: {}, 分类: {}, 标题: {}",
                        pictureId, imageTagsAndTile.tags(), imageTagsAndTile.category(), imageTagsAndTile.title());

                // 通知前端处理成功
                if (userId != null) {
                    webSocketMessageService.notifyAiProcessSuccess(userId, pictureId,
                            imageTagsAndTile.title(), imageTagsAndTile.category(), imageTagsAndTile.tags());
                }
            } else {
                log.error("更新图片AI信息失败，图片ID: {}", pictureId);

                // 通知前端处理失败
                if (userId != null) {
                    webSocketMessageService.notifyAiProcessError(userId, pictureId, "数据库更新失败");
                }
            }

        } catch (Exception e) {
            log.error("异步处理图片AI标签失败，图片ID: {}, URL: {}", pictureId, pictureUrl, e);

            // 通知前端处理失败
            if (userId != null) {
                webSocketMessageService.notifyAiProcessError(userId, pictureId, e.getMessage());
            }
        }
    }
}
